#import <CoreFoundation/CoreFoundation.h>
#import <Foundation/Foundation.h>
#import <Foundation/NSFileManager.h>
#import <UIKit/UIWindow.h>
#import <UIKit/UIView-Hierarchy.h>
#import <UIKit/UIHardware.h>
#import <UIKit/UITableCell.h>
#import <CoreGraphics/CGColor.h>
#import <CoreGraphics/CoreGraphics.h>
#import <UIKit/UIKit.h>
#import <UIKit/UINavigationItem.h>
#import <UIKit/UISegmentedControl.h>
#import <UIKit/UITextView.h>
#import <UIKit/UIPreferencesTable.h>
#import <UIKit/UIPreferencesTableCell.h>
#import <UIKit/UIPreferencesTextTableCell.h>
#import <UIKit/UIPreferencesControlTableCell.h>
#import <UIKit/UISwitchControl.h>
#import <UIKit/CDStructures.h>
#import <UIKit/UINavigationBar.h>
#import <UIKit/UINavigationItem.h>
#import <WebCore/WebCoreCache.h>
#import <GraphicsServices/GraphicsServices.h>
#import "SpringSwitches.h"
#include <dlfcn.h>
#include <stdlib.h>
#include <stdio.h>
#include <notify.h>
#define UIMouseUp 1<<6
#define UIMouseExitedUp 1<<7 
#define SS_VERSION "0.3a"

@implementation TestUITable

-(id)initWithFrame:(CGRect) rect andArray:(NSMutableArray*) a {
	self = [super initWithFrame: rect];
	dataArray = a;
	[dataArray retain];
	
	
	[self setDelegate:self];
	[self setDataSource: self];

	return self;
}
- (void)runCommand: (int) commandTxt {
/*"/bin/launchctl stop %@", @"com.apple.SpringBoard"*/
	whichAction2 = [NSString stringWithFormat: commandTxt];
	char *cmd2 = [whichAction2 UTF8String];
	FILE *fp2 = popen(cmd2, "r");
	if (fp2 == NULL) {
		NSLog(@"popen failed"); 
		exit(1);
	}

   NSString *riz2 = @"";
   int c2;
   int kBlockSize = 512;

   do {
       char buf2[kBlockSize];
       c2 = fread(buf2, sizeof(char), kBlockSize, fp2);
       if (c2 <= 0) break;
       buf2[c2] = '\0';   
       riz2 = [riz2 stringByAppendingString:
           [NSString stringWithCString:buf2 encoding:1]];
   } while (1);
}
/*- (void)tableRowSelected:(NSNotification*)notification {
UITable* actColum = [notification object];
int actRowId = [actColum selectedRow];
[actRowId setValue:1];
}*/

- (void) switchControlEvent1:(id)ctl {
	if ( [[ctl valueForKey:@"value"] boolValue]) {
		whichAction = [NSString stringWithFormat:@"/bin/mv %@ %@",
		@"Applications/WiFi.app/Info.bak",
		@"Applications/WiFi.app/Info.plist"];
		[self runCommand: whichAction];
	} else {
		whichAction = [NSString stringWithFormat:@"/bin/mv %@ %@",
		@"Applications/WiFi.app/Info.plist",
		@"Applications/WiFi.app/Info.bak"];
		[self runCommand: whichAction];
	}
}
- (void) switchControlEvent3:(id)ctl {
	if ( [[ctl valueForKey:@"value"] boolValue]) {
		whichAction = [NSString stringWithFormat:@"/bin/mv %@ %@",
		@"Applications/SSH.app/Info.bak",
		@"Applications/SSH.app/Info.plist"];
		[self runCommand: whichAction];
	} else {
		whichAction = [NSString stringWithFormat:@"/bin/mv %@ %@",
		@"Applications/SSH.app/Info.plist",
		@"Applications/SSH.app/Info.bak"];
		[self runCommand: whichAction];
	}
}
- (void) switchControlEvent2:(id)ctl {
	if ( [[ctl valueForKey:@"value"] boolValue]) {
		whichAction = [NSString stringWithFormat:@"/bin/mv %@ %@",
		@"Applications/SpringSwitches.app/Switches.bak",
		@"Applications/SpringSwitches.app/Switches.plist"];
		[self runCommand: whichAction];
	} else {
		whichAction = [NSString stringWithFormat:@"/bin/mv %@ %@",
		@"Applications/SpringSwitches.app/Switches.plist",
		@"Applications/SpringSwitches.app/Switches.bak"];
		[self runCommand: whichAction];
	}
}
-(int)numberOfRowsInTable:(UITable*)table{
	NSLog(@"numberOfRowsInTable:%d",[dataArray count]);
	return [dataArray count];
}
-(UITableCell*)table:(UITable*)table cellForRow:(int)row column:(int)column{
	NSLog(@"table:cellforrow:%d column:%d",row,column);
	UIImageAndTextTableCell *cell = [[UIImageAndTextTableCell alloc] init];
	[cell setTitle:[dataArray objectAtIndex:row]];
	if(row==0){
		UISwitchControl *switchControl = [(UIView *)[UISwitchControl alloc] initWithFrame:CGRectMake(210.0f, 11.0f, 114.0f, 45.0f)];
		[switchControl addTarget:self action:@selector(switchControlEvent1: ) forEvents:UIMouseUp];
		[switchControl addTarget:self action:@selector(switchControlEvent1: ) forEvents:UIMouseExitedUp];
		[switchControl setAlternateColors: YES];
		NSString *str = @"Applications/WiFi.app/Info.plist";
		FILE *fp;
		if(fp = fopen([str UTF8String], "r")){
			[switchControl setValue: 1.0f ];
		} else {
			[switchControl setValue: 0.0f ];
		}
		[cell addSubview:switchControl];
	} else if(row==1){
		UISwitchControl *switchControl = [(UIView *)[UISwitchControl alloc] initWithFrame:CGRectMake(210.0f, 11.0f, 114.0f, 45.0f)];
		[switchControl addTarget:self action:@selector(switchControlEvent3: ) forEvents:UIMouseUp];
		[switchControl addTarget:self action:@selector(switchControlEvent3: ) forEvents:UIMouseExitedUp];
		[switchControl setAlternateColors: YES];
		NSString *str = @"Applications/SSH.app/Info.plist";
		FILE *fp;
		if(fp = fopen([str UTF8String], "r")){
			[switchControl setValue: 1.0f ];
		} else {
			[switchControl setValue: 0.0f ];
		}
		[cell addSubview:switchControl];
	} else if(row==2) {
		UISwitchControl *switchControl2 = [(UIView *)[UISwitchControl alloc] initWithFrame:CGRectMake(210.0f, 11.0f, 114.0f, 45.0f)];
		[switchControl2 addTarget:self action:@selector(switchControlEvent2:) forEvents:UIMouseUp];
		[switchControl2 addTarget:self action:@selector(switchControlEvent2:) forEvents:UIMouseExitedUp];
		NSString *str = @"Applications/SpringSwitches.app/Switches.plist";
		FILE *fp;
		if(fp = fopen([str UTF8String], "r")){
			[switchControl2 setValue: 1.0f ];
		} else {
			[switchControl2 setValue: 0.0f ];
		}
		[cell addSubview:switchControl2];
	}
	[cell setShowSelection: NO];
	return cell;
}

@end		
		
@implementation SpringSwitches

- (void)dismissAlert:(NSTimer *)why
{
    [self terminateWithSuccess];
}

- (void)runCommand: (int) commandTxt {
/*"/bin/launchctl stop %@", @"com.apple.SpringBoard"*/
	whichAction2 = [NSString stringWithFormat: commandTxt];
	char *cmd2 = [whichAction2 UTF8String];
	FILE *fp2 = popen(cmd2, "r");
	if (fp2 == NULL) {
		NSLog(@"popen failed"); 
		exit(1);
	}

   NSString *riz2 = @"";
   int c2;
   int kBlockSize = 512;

   do {
       char buf2[kBlockSize];
       c2 = fread(buf2, sizeof(char), kBlockSize, fp2);
       if (c2 <= 0) break;
       buf2[c2] = '\0';   
       riz2 = [riz2 stringByAppendingString:
           [NSString stringWithCString:buf2 encoding:1]];
   } while (1);
}
- (void) navigationBar: (UINavigationBar*) navBar buttonClicked: (int) button 
{
	switch (button) 
	{
		case 0:
			NSLog(@"Termination requested by user.");
			NSArray *buttons = [NSArray arrayWithObjects:@"OK", nil];
			int aboutAlertText = [NSString stringWithFormat:@"SpringSwitches %@ by Jeppe Bijker. Thanks to Chris McDonald, Erica Sadun, iPhoneGameOver.com and iPhoneDevDocs.com and CocoaDev.com for their awesome documentation! For help mail to: iphone@jeppeb.nl. REMEMBER TO PRESS Exit AND RESTART SPRINGBOARD!", @SS_VERSION];
			[self setAlertTitle:@"(C) Jeppe Bijker" andAlertText: aboutAlertText andContext: @"about" andButtons: buttons andNumberOfRows:@"1" andDefaultButtonIndex:@"0"];
		break;
		case 1:
			NSLog(@"Termination requested by user.");
			NSArray *buttons2 = [NSArray arrayWithObjects:@"Go!", @"Cancel", nil];
			[self setAlertTitle:@"Exit and restart SpringBoard?" andAlertText: @"  " andContext: @"exit" andButtons: buttons2 andNumberOfRows:@"1" andDefaultButtonIndex:@"1"];
		break;
		default:
			NSLog(@"Should never reach here");
	}
}
-(void) setAlertTitle: (int) alertTitle andAlertText: (int) alertText andContext: (int)contextTxt andButtons: (int) buttons andNumberOfRows: (int) nmbRows andDefaultButtonIndex: (int) dftBttn
{
	UIAlertSheet *myAlert2;
	myAlert2 = [[UIAlertSheet alloc] initWithTitle:alertTitle  buttons:buttons defaultButtonIndex:dftBttn delegate:self context:contextTxt];
	if(alertText!=NULL)[myAlert2 setBodyText:alertText];

	if(nmbRows==@"1")[myAlert2 setNumberOfRows: 1];

	[myAlert2 setRunsModal:NO];
	[myAlert2 popupAlertAnimated:YES];
}
- (void)alertSheet:(UIAlertSheet*)sheet buttonClicked:(int)button
{
	if ( button == 1 ){
		NSLog(@"button1");
		if([sheet context]==@"about"){		
		    [sheet dismiss];
		} else {
			notify_post("com.apple.language.changed");   
		}
	} else if ( button == 2 ) {
		    [sheet dismiss];
	}
}
/*
- (void)tableRowSelected:(NSNotification*)notification {
UITable* actColum = [notification object];
int actRowId = [actColum selectedRow];
	[self setAlertTitle:@"h" andAlertText: actRowId];
}*/











#pragma mark ----------------Delegate Methods----------------

- (void) switchControlEvent1:(id)ctl {
	if ( [[ctl valueForKey:@"value"] boolValue]) {
		whichAction = [NSString stringWithFormat:@"/bin/mv %@ %@",
		@"Applications/WiFi.app/Info.bak",
		@"Applications/WiFi.app/Info.plist"];
		[self runCommand: whichAction];
	} else {
		whichAction = [NSString stringWithFormat:@"/bin/mv %@ %@",
		@"Applications/WiFi.app/Info.plist",
		@"Applications/WiFi.app/Info.bak"];
		[self runCommand: whichAction];
	}
}
- (void) switchControlEvent3:(id)ctl {
	if ( [[ctl valueForKey:@"value"] boolValue]) {
		whichAction = [NSString stringWithFormat:@"/bin/mv %@ %@",
		@"Applications/SSH.app/Info.bak",
		@"Applications/SSH.app/Info.plist"];
		[self runCommand: whichAction];
	} else {
		whichAction = [NSString stringWithFormat:@"/bin/mv %@ %@",
		@"Applications/SSH.app/Info.plist",
		@"Applications/SSH.app/Info.bak"];
		[self runCommand: whichAction];
	}
}
- (void) switchControlEvent2:(id)ctl {
	if ( [[ctl valueForKey:@"value"] boolValue]) {
		whichAction = [NSString stringWithFormat:@"/bin/mv %@ %@",
		@"Applications/SpringSwitches.app/Switches.bak",
		@"Applications/SpringSwitches.app/Switches.plist"];
		[self runCommand: whichAction];
	} else {
		whichAction = [NSString stringWithFormat:@"/bin/mv %@ %@",
		@"Applications/SpringSwitches.app/Switches.plist",
		@"Applications/SpringSwitches.app/Switches.bak"];
		[self runCommand: whichAction];
	}
}

- (void) switchControlPasswordEvent:(id)ctl {
	[self setAlertTitle:@"Not working yet..." andAlertText: @"I'm sorry but this function is not working yet... :)" andContext: @"about" andButtons: [NSArray arrayWithObjects:@"OK", nil] andNumberOfRows:@"1" andDefaultButtonIndex:@"0"];

}

- (void)tableRowSelected:(NSNotification *)notification
{
	NSLog(@"selected row %d", [table selectedRow]);
	if ([table selectedRow] == 8)
	{
		int aboutAlertText = [NSString stringWithFormat:@"SpringSwitches version %@ by Jeppe Bijker.", @SS_VERSION];
		[self setAlertTitle:@"(C) Jeppe Bijker" andAlertText: aboutAlertText andContext: @"about" andButtons: [NSArray arrayWithObjects:@"OK", nil] andNumberOfRows:@"1" andDefaultButtonIndex:@"0"];
	} 
	else if([table selectedRow] == 9)
	{
		NSURL *infoURL = [NSURL URLWithString:@"http://www.jeppeb.nl"];
		[self openURL:infoURL]; 	
	} else if ([table selectedRow] == 10){
		NSString *encodedSubject = [NSString stringWithFormat:@"SUBJECT=%@", [@"Help regarding SpringSwitches" stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]; 
		NSString *encodedBody = [NSString stringWithFormat:@"BODY=%@", [@"Hey Jeppe,\n\n" stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]]; 
		NSString *encodedTo = [@"iphone@jeppeb.nl" stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]; 
		NSString *encodedURLString = [NSString stringWithFormat:@"mailto:%@?%@&%@", encodedTo, encodedSubject, encodedBody]; 
		NSURL *mailtoURL = [NSURL URLWithString:encodedURLString]; 
		[self openURL:mailtoURL]; 
	}

}

#pragma mark ---------------Datasource Methods---------------
- (int)numberOfGroupsInPreferencesTable:(UIPreferencesTable *)table
{
	return 3;
}

- (int)preferencesTable:(UIPreferencesTable *)table numberOfRowsInGroup:(int)group
{
	switch (group)
	{
		case 0: return 3;
		case 1: return 2;
		case 2: return 3;
	}
}

- (UIPreferencesTableCell *)preferencesTable:(UIPreferencesTable *)table cellForGroup:(int)group
{
	UIPreferencesTableCell *cell = [[UIPreferencesTableCell alloc] init];
	
	return [cell autorelease];
}

- (UIPreferencesTableCell *)preferencesTable:(UIPreferencesTable *)table cellForRow:(int)row inGroup:(int)group
{
	if (group == 0)
	{
		switch (row)
		{
			case 0:
			{
				UIPreferencesControlTableCell *cell = [[UIPreferencesControlTableCell alloc] init];
				[cell setTitle:@"WiFi"];
				/*[cell setIcon:[UIImage applicationImageNamed: @"icon.png"]]; *************TODO: ADD IMAGES */
				UISwitchControl *switchControl = [[UISwitchControl alloc] initWithFrame:CGRectMake(200., 10., 50., 20.)];
				[switchControl setAlternateColors:YES];
				NSString *str = @"Applications/WiFi.app/Info.plist";
				FILE *fp;
				if(fp = fopen([str UTF8String], "r")){
					[switchControl setValue: 1.0f ];
				} else {
					[switchControl setValue: 0.0f ];
				}
				[switchControl addTarget:self action:@selector(switchControlEvent:) forEvents:UIMouseUp];
				[switchControl addTarget:self action:@selector(switchControlEvent:) forEvents:UIMouseExitedUp];
				[cell setControl:switchControl];
				[cell setShowSelection: NO];
				[switchControl release];
				return [cell autorelease];
				break;
			}
			case 1:
			{
				UIPreferencesControlTableCell *cell = [[UIPreferencesControlTableCell alloc] init];
				[cell setTitle:@"SSH"];
				UISwitchControl *switchControl = [[UISwitchControl alloc] initWithFrame:CGRectMake(200., 10., 50., 20.)];
				[switchControl setAlternateColors:YES];
				NSString *str = @"Applications/SSH.app/Info.plist";
				FILE *fp;
				if(fp = fopen([str UTF8String], "r")){
					[switchControl setValue: 1.0f ];
				} else {
					[switchControl setValue: 0.0f ];
				}
				[switchControl addTarget:self action:@selector(switchControlEvent3:) forEvents:UIMouseUp];
				[switchControl addTarget:self action:@selector(switchControlEvent3:) forEvents:UIMouseExitedUp];
				[cell setControl:switchControl];
				[cell setShowSelection: NO];
				[switchControl release];
				return [cell autorelease];
				break;
			}
			case 2:
			{
				UIPreferencesControlTableCell *cell = [[UIPreferencesControlTableCell alloc] init];
				[cell setTitle:@"Icon switches"];
				UISwitchControl *switchControl = [[UISwitchControl alloc] initWithFrame:CGRectMake(200., 10., 50., 20.)];
				NSString *str = @"Applications/SpringSwitches.app/Switches.plist";
				FILE *fp;
				if(fp = fopen([str UTF8String], "r")){
					[switchControl setValue: 1.0f ];
				} else {
					[switchControl setValue: 0.0f ];
				}
				[switchControl addTarget:self action:@selector(switchControlEvent2:) forEvents:UIMouseUp];
				[switchControl addTarget:self action:@selector(switchControlEvent2:) forEvents:UIMouseExitedUp];
				[cell setControl:switchControl];
				[cell setShowSelection: NO];
				[switchControl release];
				return [cell autorelease];
				break;
			}
		}
	} 
	else if (group == 1) 
	{
		switch (row)
		{
			case 0:
			{
				UIPreferencesControlTableCell *cell = [[UIPreferencesControlTableCell alloc] init];
				[cell setTitle:@"Use password"];
				UISwitchControl *switchControl = [[UISwitchControl alloc] initWithFrame:CGRectMake(200., 10., 50., 20.)];
				[cell setControl:switchControl];
				[switchControl addTarget:self action:@selector(switchControlPasswordEvent:) forEvents:UIMouseUp];
				[switchControl addTarget:self action:@selector(switchControlPasswordEvent:) forEvents:UIMouseExitedUp];
				[cell setShowSelection: NO];
				[switchControl release];
				return [cell autorelease];
				break;

			}
			case 1:
			{
				UIPreferencesTextTableCell *cell = [[UIPreferencesTextTableCell alloc] init];
				[cell setTitle:@"Password"];
				[cell setValue:@"password"];
				[[cell textField] setSecure:YES];
				return [cell autorelease];
			}
		}
	} 
	else if (group == 2) 
	{
		switch (row)
		{
			case 0:
			{
							/*[[cell titleTextLabel] setWrapsText:YES];
				/*[[cell titleTextLabel] setFont:[NSClassFromString(@"WebFontCache") createFontWithFamily:@"Helvetica" traits:2 size:10.]]; */
				UIPreferencesTableCell *cell = [[UIPreferencesTableCell alloc] init];
				[cell setTitle:[NSString stringWithFormat:@"Version %@ (C) Jeppe Bijker", @SS_VERSION]];
				return [cell autorelease];
			}
			case 1:
			{
				UIPreferencesTableCell *cell = [[UIPreferencesTableCell alloc] init];
				[cell setTitle:@"www.jeppeb.nl/iphone"];
				float blue[4]		= { 0.0f, 0.0f, 1.0f, 1.0f };
				float color2[4]		= { 0.0f, 0.0f, 1.0f, 0.7f };
				[[cell titleTextLabel] setColor:CGColorCreate(CGColorSpaceCreateDeviceRGB(), blue)];
				[[cell titleTextLabel] setHighlightedColor:CGColorCreate(CGColorSpaceCreateDeviceRGB(), color2)];
				return [cell autorelease];
			}
			case 2:
			{
				UIPreferencesTableCell *cell = [[UIPreferencesTableCell alloc] init];
				[cell setTitle:@"iphone@jeppeb.nl"];
				float blue[4]		= { 0.0f, 0.0f, 1.0f, 1.0f };
				float color2[4]		= { 0.0f, 0.0f, 1.0f, 0.7f };
				[[cell titleTextLabel] setColor:CGColorCreate(CGColorSpaceCreateDeviceRGB(), blue)];
				[[cell titleTextLabel] setHighlightedColor:CGColorCreate(CGColorSpaceCreateDeviceRGB(), color2)];
				return [cell autorelease];
			}
		}
	}
}














- (void)applicationDidFinishLaunching:(id)unused
{
	UIWindow *window;
 
	struct CGRect rect	= [UIHardware fullScreenApplicationContentRect];
	struct CGRect trect	= [UIHardware fullScreenApplicationContentRect];
    rect.origin.x = rect.origin.y = 0.0f;
	trect.size.height	= trect.size.height / 2;

  	window = [[UIWindow alloc] initWithContentRect: rect];
	mainView = [[UIView alloc] initWithFrame: rect];

	[window orderFront: self];
	[window makeKey: self];
	[window _setHidden: NO];
	[window setContentView: mainView];

	
	table = [[UIPreferencesTable alloc] initWithFrame: CGRectMake(0.0f, 45.0f, rect.size.width, (rect.size.height-45.0f))];
	[table setDataSource: self];
    [table setDelegate: self];
	
	
	UINavigationBar *navBar	= [[UINavigationBar alloc] initWithFrame: CGRectMake(0.0f, 0.0f, 320.0f, 45.0f)];
	[navBar showLeftButton:@"Exit" withStyle:1 rightButton:@"About" withStyle:3];
	UINavigationItem *zTitle = [[UINavigationItem alloc] initWithTitle:@"SpringSwitches"];
[navBar pushNavigationItem:zTitle];
[zTitle release];
	[navBar setBarStyle: 0];
	[navBar setDelegate: self];

	float blue[4]		= { 0.0f, 0.0f, 1.0f, 1.0f };
	float color2[4]		= { 0.0f, 1.0f, 0.0f, 0.9f };
/* Initialize a text label with static, uneditable text */
	UITextLabel *_title = [[UITextLabel alloc] initWithFrame: CGRectMake(0.0f, 250.0f, 320.0f, 230.0f)];
	[_title setText: [NSString stringWithFormat:@"SpringSwitches %@ by Jeppe Bijker. Thanks to Chris McDonald, Erica Sadun, iPhoneGameOver.com and iPhoneDevDocs.com and CocoaDev.com for their awesome documentation! For help mail to: iphone@jeppeb.nl. REMEMBER TO PRESS Exit AND RESTART SPRINGBOARD!", @SS_VERSION]];
	[_title setColor: CGColorCreate(CGColorSpaceCreateDeviceRGB(), blue)];
	[_title setShadowColor: CGColorCreate(CGColorSpaceCreateDeviceRGB(), color2)];
	[_title setWrapsText: true];
	
	[mainView addSubview:navBar];
	[table reloadData];
	[mainView addSubview: table];
	/*[mainView addSubview: _title];*/
}
- (void)applicationWillTerminate {
	/*notify_post("com.apple.language.changed"); ************************/
}
@end

